package com.guldan.thrall.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.guldan.core.controller.BaseController;
import com.guldan.core.dubbo.client.ResponseDTO;
import com.guldan.core.response.ResponseJson;
import com.guldan.core.search.Pagination;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.project.ProjectDTO;
import com.guldan.jaina.dto.project.ProjectSearchDTO;
import com.guldan.jaina.dto.projectattach.ProjectAttachDTO;
import com.guldan.jaina.dto.projectattach.ProjectAttachSearchDTO;
import com.guldan.jaina.provider.IProjectProvider;
import com.guldan.thrall.constant.Constant;

/**
 * Created by Silas.
 * Date: 2016/11/10
 * Time: 22:06
 */
@Controller
@RequestMapping("/project")
public class ProjectController extends BaseController {


    @Autowired
    private IProjectProvider iProjectProvider;

    //获取单个项目
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ResponseJson
    public
    @ResponseBody
    ProjectDTO get(@RequestBody ProjectDTO dto) {
        ResponseDTO<ProjectDTO> response = iProjectProvider.get(dto.getProjectId());
        return response.getData();
    }

    //新增/保存单个项目
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseJson
    public
    @ResponseBody
    ProjectDTO save(@RequestBody ProjectDTO dto) throws Exception {
        ResponseDTO<ProjectDTO> response = iProjectProvider.save(dto);

        if (response.isSuccess())
            return response.getData();
        else {
            throw response.getException();
        }
    }

    //删除单个项目
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseJson
    public
    @ResponseBody
    Boolean delete(@RequestBody ProjectDTO dto) {
        ResponseDTO<Boolean> response = iProjectProvider.delete(dto.getProjectId());
        return response.getData();
    }

    //获取项目列表
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseJson
    public
    @ResponseBody
    Pagination<ProjectDTO> list(@RequestBody ProjectSearchDTO dto) {
        ResponseDTO<Pagination<ProjectDTO>> response = iProjectProvider.list(dto);
        return response.getData();
    }

    //获取某个主管部门下的项目列表
    @RequestMapping(value = "/listForOrg", method = RequestMethod.POST)
    @ResponseJson
    public
    @ResponseBody
    List<ProjectDTO> listForOrg(@RequestBody ProjectSearchDTO dto) {
        ResponseDTO<List<ProjectDTO>> response = iProjectProvider.listForOrg(dto);
        return response.getData();
    }

    @RequestMapping(value = "/uploadAttach", method = RequestMethod.POST)
    @ResponseJson
    public @ResponseBody ProjectAttachDTO uploadAttach(HttpServletRequest request) {
    	ProjectAttachDTO dto = new ProjectAttachDTO();
    	dto.setAttachName(request.getParameter("attachName"));
    	dto.setAttachTypeCode(request.getParameter("attachTypeCode"));
    	
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            Iterator<String> iter = multiRequest.getFileNames();
            if (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null) {
                	String subDirectory = DateUtil.toLocaleString(new Date(), "yyyyMMdd");
                	String filePath = request.getRealPath("/") + Constant.ATTACHMENT_PATH_BASE + subDirectory;
                	String urlPath = "/" + Constant.ATTACHMENT_PATH_BASE + subDirectory;
                	File f = new File(filePath);
                	if (!f.exists())
                		f.mkdirs();
                    String path = filePath + "/" + file.getOriginalFilename();
                    dto.setAttachUrl(urlPath + "/" + file.getOriginalFilename());
                    try {
						file.transferTo(new File(path));
					} catch (IllegalStateException | IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }
            }
        }

        return dto; 
    }

//	@RequestMapping(value = "/downAttach", method = RequestMethod.POST)
//    public ResponseEntity<byte[]> downAttach(@RequestBody ProjectAttachSearchDTO dto) throws IOException {
//    	ResponseDTO<ProjectAttachDTO> response = iProjectProvider.getProjectAttach(dto);
//    	String attachUrl = response.getData().getAttachUrl();
//    	return this.downloadExcel(attachUrl, response.getData().getAttachName());
//    }

	@RequestMapping(value = "/downAttach", method = RequestMethod.GET)
    public ResponseEntity<byte[]> downAttach(HttpServletRequest request) throws IOException {
    	ProjectAttachSearchDTO dto = new ProjectAttachSearchDTO();
    	dto.setAttachId(Integer.valueOf(request.getParameter("attachId")));
    	ResponseDTO<ProjectAttachDTO> response = iProjectProvider.getProjectAttach(dto);
    	String attachUrl = response.getData().getAttachUrl();
    	return this.downloadExcel(attachUrl, response.getData().getAttachName());
    }
}
